//! 固碳与热力抵扣备份
var chartDom = document.getElementById("GTreli");
var myChart = echarts.init(chartDom);
var option;

option = {
  title: {
    show: true, //false
    text: "固碳与热力抵扣", //主标题文本
    textStyle: {
      color: "rgba(0, 0, 0, 1)", //'red'，字体颜色
      fontSize: 15, //字体大小
      lineHeight: 20, //字体行高
    },
    // textAlign: "auto", //整体（包括 text 和 subtext）的水平对齐
    // textVerticalAlign: "auto", //整体（包括 text 和 subtext）的垂直对齐
    // padding: 0, //[5,10] | [ 5,6, 7, 8] ,标题内边距
    left: "4.5%", //'5' | '5%'，title 组件离容器左侧的距离
    right: "auto", //'title 组件离容器右侧的距离
    top: "2%", //title 组件离容器上侧的距离
    bottom: "auto", //title 组件离容器下侧的距离
  },
  color: ["rgba(32, 159, 133, 1)", "rgba(230, 239, 229, 1)"],
  tooltip: {
    trigger: "axis",
  },
  xAxis: {
    type: "category",
    data: ["3月", "4月", "5月", "6月", "7月", "8月"],
  },
  yAxis: {
    type: "value",
  },
  series: [
    {
      data: [120, 200, 150, 80, 70, 110],
      type: "bar",
      stack: "a",
      name: "a",
      itemStyle: {
        normal: {
          //柱形图圆角设置
          barBorderRadius: [20, 20, 0, 0], //柱形图圆角设置
        },
      },
      barCategoryGap: 35,
      barWidth: "25%",
    },
    {
      data: [30, 300, 100, 20, 10, 200],
      type: "bar",
      stack: "b",
      name: "d",
      itemStyle: {
        normal: {
          //柱形图圆角设置
          barBorderRadius: [20, 20, 0, 0], //柱形图圆角设置
        },
      },
      barCategoryGap: 35,
      barWidth: "25%",
    },
  ],
};

option && myChart.setOption(option);

//! 全厂排放趋势备份
var chartDom = document.getElementById("QCpaifang");
var myCharts = echarts.init(chartDom);
var option;

option = {
  title: {
    show: true, //false
    text: "全厂排放趋势", //主标题文本
    textStyle: {
      color: "rgba(0, 0, 0, 1)", //'red'，字体颜色
      fontSize: 15, //字体大小
      lineHeight: 20, //字体行高
    },
    // textAlign: "auto", //整体（包括 text 和 subtext）的水平对齐
    // textVerticalAlign: "auto", //整体（包括 text 和 subtext）的垂直对齐
    // padding: 0, //[5,10] | [ 5,6, 7, 8] ,标题内边距
    left: "6.5%", //'5' | '5%'，title 组件离容器左侧的距离
    right: "auto", //'title 组件离容器右侧的距离
    top: "2%", //title 组件离容器上侧的距离
    bottom: "auto", //title 组件离容器下侧的距离
  },
  tooltip: {
    trigger: "axis",
  },
  // color: ["rgba(48, 217, 160, 1)"],
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: ["3月", "4月", "5月", "6月", "7月", "8月"],
    triggreEvent: true,
  },
  yAxis: {
    type: "value",
    triggreEvent: true,
  },
  series: [
    {
      // symbol: "none", //去掉折线图中的节点
      smooth: true, //true 为平滑曲线，false为直线
      data: [1, 4, 2, 6, 5, 1],
      type: "line",
      areaStyle: {
        normal: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 1, color: "rgba(145, 255, 102, 0)" },
            { offset: 0.5, color: "rgba(72, 208, 162, 0.1)" },
            { offset: 0, color: "rgba(57, 227, 170, 0.2)" },
          ]),
        },
      },
      color: {
        type: "linear",
        x: 0,
        y: 0,
        x2: 0.5,
        y2: 1,
        colorStops: [
          {
            offset: 0,
            color: "rgba(82, 204, 163, 0)", // 0% 处的颜色
          },
          {
            offset: 1,
            color: "rgba(48, 217, 160, 1)", // 100% 处的颜色
          },
        ],
        globalCoord: false, // 缺省为 false
      },
    },
  ],
};

option && myCharts.setOption(option);
// 监听折线图数据项的鼠标移动事件
myCharts.on("click", function (params) {
  if (params.componentType === "series") {
    // console.log(params.value);
  }
});
function clearText() {
  document.getElementById("inputId").value = "";
}
//! 排放强度
var chartDom = document.getElementById("PFqiangdu");
var myChart = echarts.init(chartDom);
var option;

option = {
  title: {
    show: true, //false
    text: "排放强度", //主标题文本
    textStyle: {
      color: "rgba(70, 78, 95, 1)", //'red'，字体颜色
      fontSize: 15, //字体大小
      lineHeight: 20, //字体行高
    },
    // textAlign: "auto", //整体（包括 text 和 subtext）的水平对齐
    // textVerticalAlign: "auto", //整体（包括 text 和 subtext）的垂直对齐
    // padding: 0, //[5,10] | [ 5,6, 7, 8] ,标题内边距
    left: "8%", //'5' | '5%'，title 组件离容器左侧的距离
    right: "auto", //'title 组件离容器右侧的距离
    top: "2%", //title 组件离容器上侧的距离
    bottom: "auto", //title 组件离容器下侧的距离
  },
  color: ["rgba(100, 161, 94, 1)"],
  tooltip: {
    trigger: "axis",
  },
  dataset: {
    source: [
      [0.4, "炼钢"],
      [0.2, "炼铁"],
      [0.3, "烧结"],
      [1.6, "焦化"],
    ],
  },
  grid: { containLabel: true },
  xAxis: [{ name: "", axisLabel: { formatter: "{value} k" } }],
  yAxis: {
    type: "category",
    //取消网格线
    // splitLine: {
    //   show: false,
    // },
    // 取消坐标轴刻度线
    // axisTick: {
    //   show: false,
    // },
    // 取消显示坐标值
    // axisLabel: {
    //     show: false
    // },
    // 取消显示坐标轴
    axisLine: {
      show: false,
    },
    // 取消显示坐标轴,坐标轴刻度,坐标值(如果是y轴,默认的网格线也会取消显示)
    // show: false
  },
  series: [
    {
      barCategoryGap: 13,
      barWidth: "40%",
      type: "bar",
      encode: {
        // Map the "amount" column to X axis.
        x: "amount",
        // Map the "product" column to Y axis
        // y: "category",
      },
      itemStyle: {
        normal: {
          //柱形图圆角设置
          barBorderRadius: [20, 20, 20, 20], //柱形图圆角设置
        },
      },
    },
  ],
};

option && myChart.setOption(option);

//! 碳产品一排放趋势
var chartDom = document.getElementById("containerOne");
var myChart1 = echarts.init(chartDom);
var option1;

option1 = {
  type: "category",
  // 标题设置
  title: { text: "碳产品一排放趋势" },
  tooltip: {
    trigger: "axis", // 设置触发类型为数据项触发
    axisPointer: {
      type: "cross", // 设置坐标轴指示器类型为十字准线
    },
    formatter: function (params) {
      // 自定义提示框内容
      var str = "";
      params.forEach(function (param) {
        str +=
          "<div class='title'>2024年6月</div>" +
          "<div class='content'><div><div class='point point-color1'></div>排放总量</div>" +
          "<span>36吨</span></div>" +
          "<div class='content'><div><div class='point point-color2'></div>同比</div>" +
          "<span style='box-sizing=border-box; text-align: end; display: flex;justify-content: end; align-items: center;'><svg t='1723528452736' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='4431' width='10%'><path d='M51.2 438.477h307.2c0 304.435-74.342 432.333-307.2 584.499 332.698-60.723 614.195-158.31 614.195-584.5h307.2L511.795 0 51.2 438.477z' fill='#E64025' p-id='4432'></path></svg>18%</span></div>" +
          "<div class='content'><div><div class='point point-color3'></div>环比</div>" +
          "<span  style='box-sizing=border-box; text-align: end; display: flex;justify-content: end; align-items: center;'><svg t='1723528928956' class='icon' viewBox='0 0 1024 1024' version='1.1' xmlns='http://www.w3.org/2000/svg' p-id='5491' data-spm-anchor-id='a313x.search_index.0.i5.45f43a81eC5Ipf' width='10%'><path d='M507.649902 1015.81158L160.153845 618.161453a21.75049 21.75049 0 0 1 16.376839-36.080224h187.565987a22.262266 22.262266 0 0 0 21.750489-22.262266 1630.774944 1630.774944 0 0 0-12.538517-207.525259C350.022825 182.895773 268.138628 87.705395 204.934264 38.574877A21.75049 21.75049 0 0 1 223.102321 0.447548C588.766434 60.837143 665.532868 470.514012 679.350826 563.401397a21.238713 21.238713 0 0 0 21.494601 18.679832h170.677372a21.75049 21.75049 0 0 1 16.120951 36.080224L540.403581 1015.81158a21.75049 21.75049 0 0 1-32.753679 0z' p-id='5492' fill='#00B42A'></path></svg>43%</span></div>";
      });
      return str;
    },
    className: "custom-tooltip",
  },
  legend: {
    // 数据标识
    data: ["人数"],
  },
  xAxis: {
    type: "category",
    boundaryGap: false,
    data: [
      "1月",
      "2月",
      "3月",
      "4月",
      "5月",
      "6月",
      "7月",
      "8月",
      "9月",
      "10月",
      "11月",
      "12月",
    ],
    axisLabel: {
      color: '#B5B5C3' // 设置 Y 轴标签的字体颜色为中灰色
    },
    axisTick: {
      show: false // 不显示刻度线
    },
    axisLine: {
      lineStyle: {
        type: 'dashed', // 设置轴线为虚线
        // 可以通过 dashOffset 和 length 来调整虚线样式
        dashOffset: 0,
        length: [5, 5] // 虚线的模式，[实线长度, 间隔长度]
      }
    }

  },
  yAxis: {
    type: "value",
    axisLabel: {
      color: '#B5B5C3' // 设置 Y 轴标签的字体颜色为中灰色
    }
  },
  series: [
    {
      data: [820, 932, 901, 934, 1290, 1330, 1320, 820, 932, 901, 934, 1290],
      type: "line",
      // symbol: 'none', // 不显示点标记
      // symbol: "circle",
      // symbolSize: 0, // 隐藏数据点的标记
      smooth: true,
      stack: "Total",
      itemStyle: {
        color: "rgba(32, 159, 133, 0.4)", // 设置折线图点的颜色为
      },
      lineStyle: {
        color: "rgba(32, 159, 133, 1)", // 设置折线颜色
        width: 5, // 设置折线宽度
        color: {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0.5,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: "rgba(82, 204, 163, 0)", // 0% 处的颜色
            },
            {
              offset: 1,
              color: "rgba(48, 217, 160, 1)", // 100% 处的颜色
            },
          ],
          globalCoord: false, // 缺省为 false
        },
      },
    },
  ],
};

option && myChart1.setOption(option1);

//! 碳产品一生命周期
var chartDom = document.getElementById("containerOneTwo");
var myChart2 = echarts.init(chartDom);
var option2;
var barData = [
  {
    data: [],
    name: "A",
    type: "bar",
    barWidth: "20%",
    stack: 'total',
  },
  {
    value: [], name: "B", type: "bar",
    barWidth: "20%",
    stack: 'total',
  }
];
for (var b = 0; b <= 6; b++) {
  let s = Math.random() * (10 - -10) + -10;
  barData[0].data.push(s);
}
// function inverse() {
barData[1].data = barData[0].data.map(function (value) {
  return value * -1;
});
// }

//调整生命周期的弧度
barDataRorder(barData);
function barDataRorder(barData) {
  for (let i = 0; i < barData.length; ++i) {
    const data = barData[i].data;
    for (let j = 0; j < barData[i].data.length; ++j) {
      const topBorder = barData[i].data[j] > 0 ? 20 : 0;
      const bottomBorder = barData[i].data[j] < 0 ? 20 : 0;
      data[j] = {
        value: data[j],
        itemStyle: {
          borderRadius: [topBorder, topBorder, bottomBorder, bottomBorder],
        },
      };
    }
  }
}

// !指定图表的配置项和数据
var option2 = {
  color: ['#209F85', '#FAC706'],
  title: {
    text: "碳产品一生命周期",
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow",
    },
    formatter: function (params) {
      // 只显示 Series A 的数据
      var result = '';
      params.forEach(function (item) {
        if (item.seriesName === 'A') {
          result += item.seriesName + ': ' + item.value + '<br/>';
        }
      });
      return result;
    }
  },
  xAxis: {
    type: "category",
    data: ["G1", "G2", "G3", "G4", "G5", "G6", "G7"],
    axisLabel: {
      color: '#B5B5C3' // 设置 Y 轴标签的字体颜色为中灰色
    },
    axisTick: {
      show: false // 不显示刻度线
    },
    axisLine: {
      lineStyle: {
        type: 'dashed', // 设置轴线为虚线
        // 可以通过 dashOffset 和 length 来调整虚线样式
        dashOffset: 0,
        length: [5, 5] // 虚线的模式，[实线长度, 间隔长度]
      }
    }
  },
  yAxis: {
    type: "value",
    axisLabel: {
      formatter: "{value}",
    },
    axisLabel: {
      color: '#B5B5C3' // 设置 Y 轴标签的字体颜色为中灰色
    }
  },
  series: barData,
};
function generateNewData() {
  var newData = [];
  for (var i = 0; i < 12; i++) {
    newData.push(Math.random() * (10 - -10) + -10);
  }
  return newData;
}
function switchTab(chartIndex) {
  var option;
  if (chartIndex === 0) {
    option = option1;
  } else {
    option = option2;
  }
  for (var i = 0; i <= option.series.length; i++) {

    if (option.series[i] != undefined) {
      var item = option.series[i];
      item.data = generateNewData();
      if (item.name == 'A') {
        item.data = generateNewData();
      }
      //反值
      if (item.name == 'B') {
        item.data = barData[0].data.map(function (value) {
          return value * -1;
        });
      }
    }
  }
  //调整弧度
  barDataRorder(barData);
  if (chartIndex === 0) {
    myChart1.setOption(option);
  } else {
    myChart2.setOption(option);
  }
}
option && myChart2.setOption(option2);
// 切换数据的函数
function switchData(tab) {
  // 移除所有选项卡的 active 类
  var tabs = document.querySelectorAll(".CarbonFootprintTitle1");
  tabs.forEach(function (tab) {
    tab.classList.remove("CarbonFootprintTitleActive");
  });
  // 添加 active 类到当前点击的选项卡
  tab.classList.add("CarbonFootprintTitleActive");
  // !切换两个图表的数据
  switchTab(0);
  switchTab(1);
}
//! 滑动折线图更新柱状图数据的函数
function updateBarData(value) {
  barData[0].data = [];
  // barData[1].value = []
  // for (var i = 0; i <= 1; i++) {
  for (var b = 0; b <= 6; b++) {
    let s = Math.random() * (10 - -10) + -10;
    barData[0].data.push(s);
  }
  //反值
  barData[1].data = barData[0].data.map(function (value) {
    return value * -1;
  });
  // }
  //调整弧度
  barDataRorder(barData);
  myChart2.setOption({
    series: barData,
  });
}
// 监听折线图数据项的鼠标移动事件
myChart1.on("mousemove", function (params) {
  if (params.componentType === "series") {
    updateBarData(params.value);
  }
});
function clearText() {
  document.getElementById("inputId").value = "";
}

// 自定义字符串,用于拼接标签
//  var loveStr = "";

//  // 自定义数组
//  var loveArr = ['喜爱一个人需要理由吗？', '需要吗？', '不需要吗？'];

//  /****普通for循环****/
//  for (let i = 0; i < loveArr.length; i++) {
//      loveStr += '<div>' + loveArr[i] + '</div>';
//  };

//  // 拼接完字符串数组后用innerHTML把它渲染到页面中
//  document.getElementById("LoveID").innerHTML = loveStr;

// 获取当前日期
const today = new Date();
// 设置日历的起始日期为本周的第一天（周一）
let startOfWeek = new Date(
  today.getFullYear(),
  today.getMonth(),
  today.getDate() - today.getDay() + 1
);
let currentYear = today.getFullYear();
let currentMonth = today.getMonth();
// function currentYear() {
//   return today.getFullYear();
// }
// function currentMonth() {
//   return today.getMonth()
// }
// 更新日历显示
function updateCalendar() {
  const monthYearElement = document.getElementById("month-year");
  monthYearElement.textContent =
    startOfWeek.getFullYear() +
    "年 " +
    startOfWeek.toLocaleString("default", { month: "long" });

  const tableBody = document.getElementById("calendar").querySelector("tbody");
  tableBody.innerHTML = ""; // 清空表格内容

  let date = new Date(startOfWeek);
  const days = ["一", "二", "三", "四", "五", "六", "日"];
  const weekRow = document.createElement("tr"); // 创建一个用于存储一周日期的行
  // 创建一个新的div元素
  var newDiv = document.createElement("div");
  // 创建一周的日期数组
  for (let i = 0; i < 7; i++) {
    const dayName = days[date.getDay()];
    const cell = document.createElement("td");
    if (
      date.getDate() === today.getDate() &&
      date.getDay() === today.getDay()
    ) {
      // 如果是今天的日期，显示“今”
      newDiv.textContent = "今";
      cell.appendChild(newDiv);
      newDiv.className = "today"; // 添加类名
    } else {
      cell.textContent = date.getDate();
    }
    weekRow.appendChild(cell); // 将日期添加到行中

    date.setDate(date.getDate() + 1); // 移动到下一天
  }

  tableBody.appendChild(weekRow); // 将包含一周日期的行添加到表格中
}

// 切换到上一周
document.getElementById("prevWeek").addEventListener("click", () => {
  startOfWeek.setDate(startOfWeek.getDate() - 7);
  updateCalendar();
});

// 切换到下一周
document.getElementById("nextWeek").addEventListener("click", () => {
  startOfWeek.setDate(startOfWeek.getDate() + 7);
  updateCalendar();
});

const monthYearElement = document.getElementById("month-year");
// 初始化日历
updateCalendar();

// 获取弹窗元素
const modal = document.getElementById("modal");
const closeModalBtn = document.getElementById("closeModalBtn");

// 打开弹窗的函数
function openModal() {
  modal.classList.add("modal-visible");
}

// 关闭弹窗的函数
function closeModal() {
  modal.classList.remove("modal-visible");
}

// 点击按钮打开弹窗
monthYearElement.addEventListener("click", () => {
  openModal();
  let currentMonth = today.getMonth();
  let currentYear = today.getFullYear();

  updateMonthYearDisplayB(currentYear, currentMonth); // 初始化显示
});

// 点击弹窗外部关闭弹窗
modal.addEventListener("click", function (event) {
  if (event.target === modal) {
    document
      .getElementById("calendarB")
      .removeChild(document.getElementById("calendarB").firstChild);

    closeModal();
  }
});

function generateCalendar(month, year) {
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const daysInMonth = lastDay.getDate();
  const firstDayOfWeek = firstDay.getDay();
  let calendarHtml = "<table>";

  // Add the header row
  calendarHtml +=
    "<tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr>";

  // Add the days of the month
  let day = 1;
  calendarHtml += "<tr>";
  for (let i = 0; i < firstDayOfWeek; i++) {
    calendarHtml += "<td></td>"; // Empty cells for the days before the first of the month
  }
  while (day <= daysInMonth) {
    calendarHtml += `<td>${day}</td>`;
    if ((day + firstDayOfWeek) % 7 === 0) {
      calendarHtml += "</tr><tr>";
    }
    day++;
  }
  calendarHtml += "</tr></table>";

  return calendarHtml;
}

function updateMonthYearDisplayB(currentYear, currentMonth) {
  document.getElementById("month-yearB").textContent = "";

  const monthNames = [
    "01月",
    "02月",
    "03月",
    "04月",
    "05月",
    "06月",
    "07月",
    "08月",
    "09月",
    "10月",
    "11月",
    "12月",
  ];
  const monthName = monthNames[currentMonth];
  document.getElementById(
    "month-yearB"
  ).textContent = `${currentYear}年 ${monthName} `;

  const calendarHtml = generateCalendar(currentMonth, currentYear);
  document.getElementById("calendarB").innerHTML = calendarHtml;
}

function changeMonth(offset) {
  currentMonth += offset;
  if (currentMonth < 0) {
    currentMonth = 11;
    currentYear -= 1;
  } else if (currentMonth > 11) {
    currentMonth = 0;
    currentYear += 1;
  }

  updateMonthYearDisplayB(currentYear, currentMonth);
}

document
  .getElementById("prev-month")
  .addEventListener("click", () => changeMonth(-1));
document
  .getElementById("next-month")
  .addEventListener("click", () => changeMonth(1));

document.getElementById("month-year").addEventListener("click", function () {
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth();

  const calendarHtml = generateCalendar(currentMonth, currentYear);
  document.getElementById("calendarB").innerHTML = calendarHtml;
  document.getElementById("calendarB").style.display = "block";
});

// 清空表格数据的函数
function clearTableData() {
  // 移除所有子元素，包括表格和其中的数据
  while (document.getElementById("calendarB").firstChild) {
    document
      .getElementById("calendarB")
      .removeChild(document.getElementById("calendarB").firstChild);
  }
}

/* 当用户点击按钮时，
在隐藏和显示下拉内容之间切换 */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// 如果用户在下拉菜单之外点击，则关闭下拉菜单
window.onclick = function (event) {
  if (!event.target.matches(".dropbtn")) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains("show")) {
        openDropdown.classList.remove("show");
      }
    }
  }
};

//  //! 当前时间
const now = new Date();

const year = now.getFullYear();
const month = ("0" + (now.getMonth() + 1)).slice(-2);
const day = ("0" + now.getDate()).slice(-2);
const hours = ("0" + now.getHours()).slice(-2);
const minutes = ("0" + now.getMinutes()).slice(-2);
const seconds = ("0" + now.getSeconds()).slice(-2);

const formattedTime = year + "." + month + "." + day;
document.getElementById("Time").innerHTML =
  document.getElementById("Time1").innerHTML =
  document.getElementById("Time2").innerHTML =
  document.getElementById("Time3").innerHTML =
  formattedTime;
// document.getElementById("Time1").innerHTML = formattedTime;

//! 监听页面缩放 
const getWindowInfo = () => {
  // const windowInfo = {
  // width: window.innerWidth,
  // hight: window.innerHeight
  // }
  // console.log(windowInfo);
  location.reload();
  };
  //! 防抖 1.5秒
  const debounce = (fn, delay) => {
    let timer;
    return function() {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn();
      }, delay);
    }
  };
  const cancalDebounce = debounce(getWindowInfo, 2000);
  
  window.addEventListener('resize', getWindowInfo);